package cc.lj.internal.core.http;

import cc.lj.internal.core.exception.SysExceptionEnum;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 注册拦截器，统一返回对象格式为HttpResult
 */
@RestControllerAdvice(basePackages = "cc.lj.internal")
public class GlobalResponseBodyHandler implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 如果已经是 HttpResult 类型，则直接返回
        if (body instanceof HttpResult) {
            return body;
        }
        // 如果不是，则包装成 HttpResult 类型
        return HttpResult.success(SysExceptionEnum.SUCCESS.getCode(),SysExceptionEnum.SUCCESS.getMessage(),body);
    }
}
